package main

// 没有main包可是会报 “ 与你运行的 Windows 版本不兼容。请查看计算机的系统信息，然后联系软件发布者。“ 的哦
import (
	"fmt"
	"github.com/garyburd/redigo/redis"
	"time"
)

/**
* @author aFun
* @data 2025/4/14 16:49
* @email: afunaaa222@163.com / 1030935903
* @address: Guangdong University of Technology, China
 */

var RedisPool *redis.Pool

func main() {
	InitRedis()
	go MonitorRanking()
	select {}
}

func MonitorRanking() {
	for {
		time.Sleep(3 * time.Second) // 每5秒查看一次排行榜
		fmt.Println("排行榜（按消耗代币数）:")
		printTopRank("lucky_draw:rank_tokens")

		fmt.Println("排行榜（按抽奖次数）:")
		printTopRank("lucky_draw:rank_drawNums")

		fmt.Println("----")
	}
}

func printTopRank(key string) {
	conn := RedisPool.Get()
	defer conn.Close()
	// ZREVRANGE key 0 9 WITHSCORES 取前10名
	values, err := redis.Values(conn.Do("ZREVRANGE", key, 0, 9, "WITHSCORES"))
	if err != nil {
		fmt.Printf("获取排行榜 %s 失败: %v\n", key, err)
		return
	}

	for i := 0; i < len(values); i += 2 {
		roleID, _ := redis.Int64(values[i], nil)
		score, _ := redis.Int64(values[i+1], nil)
		fmt.Printf("  %2d. RoleID: %d - 分数: %d\n", i/2+1, roleID, score)
	}
}

func InitRedis() {
	address := "127.0.0.1:6379"
	maxIdle := 16
	maxActive := 9
	IdleTimeout := time.Duration(300)

	RedisPool = &redis.Pool{
		MaxIdle:     maxIdle,
		MaxActive:   maxActive,
		IdleTimeout: IdleTimeout,
		Wait:        true, // 没连接时等待而不是报错   报了一次错误 ==> 获取排行榜 lucky_draw:rank_drawNums 失败: redigo: connection pool exhausted
		Dial: func() (redis.Conn, error) {
			return redis.Dial("tcp", address, redis.DialDatabase(0))
		},
	}
}
